package com.aiden.app.common.http

import com.google.gson.JsonParseException
import org.json.JSONException
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.UnknownHostException
import java.text.ParseException

/**
 *
 * 异常处理
 * @author yanggeng
 * @date 2018/12/20 下午5:20
 */
object ServerErrorHandling {

    fun handling(t: Throwable, method: (ExceptionReason) -> Unit) {
        when (t) {
            is HttpException -> method(ExceptionReason.BAD_NETWORK)
            is ConnectException, is UnknownHostException -> method(ExceptionReason.CONNECT_ERROR)
            is InterruptedIOException -> method(ExceptionReason.CONNECT_TIMEOUT)
            is JsonParseException, is JSONException, is ParseException -> method(ExceptionReason.PARSE_ERROR)
            else -> method(ExceptionReason.UNKNOWN_ERROR)
        }
    }

    fun handling(t: Throwable, onExceptionHandling: OnExceptionHandling) {
        when (t) {
            is HttpException -> onExceptionHandling.onExceptionHandle(ExceptionReason.BAD_NETWORK)
            is ConnectException, is UnknownHostException -> onExceptionHandling.onExceptionHandle(ExceptionReason.CONNECT_ERROR)
            is InterruptedIOException -> onExceptionHandling.onExceptionHandle(ExceptionReason.CONNECT_TIMEOUT)
            is JsonParseException, is JSONException, is ParseException -> onExceptionHandling.onExceptionHandle(ExceptionReason.PARSE_ERROR)
            else -> onExceptionHandling.onExceptionHandle(ExceptionReason.UNKNOWN_ERROR)
        }
    }

    interface OnExceptionHandling {
        fun onExceptionHandle(exception: ExceptionReason)
    }
}